/* Gère les connexions entre hotes */

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netinet/in.h>

#include "../include/connexions.h"

#define BACKLOG 1024

/* Create the listening socket */
int create_socket(int ip, int port) {
	int listening_socket;
	struct sockaddr_in servaddr; // socket address struct

	if ((listening_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("socket");
		exit(EXIT_FAILURE);
	}

	int on = 1;
	int status = setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR, &on,
			sizeof(on));

	/* Set all bytes in socket address structure to
	 zero, and fill in the relevant data members */

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_addr.s_addr = htonl(ip);
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);

	/* Bind our socket addresss to the
	 listening socket, and call listen() */

	if (bind(listening_socket, (struct sockaddr *) &servaddr, sizeof(servaddr))
			< 0) {
		perror("bind");
		exit(EXIT_FAILURE);
	}

	//max = listening_socket;

	/* Wait for a connection, then accept() it */

	if (listen(listening_socket, BACKLOG) < 0) {
		perror("listen");
		exit(EXIT_FAILURE);
	}

	return listening_socket;
}

char* new_client_name(int socket, listeClients liste) {
	char* name = malloc(sizeof(char) * 20);

	// On récupère le pseudo du nouveau client !
	char entrezpseudo[] = "Bienvenue sur le serveur. Entrez un pseudo :\n";
	char autrepseudo[] = "Pseudo déjà utilisé. Réessayez :\n";

	sendline(socket, entrezpseudo, strlen(entrezpseudo));
	readline(socket, name, 20);

	while (pseudoExiste(liste, name)) {
		memset(name, 0, 20);
		sendline(socket, autrepseudo, strlen(autrepseudo));
		readline(socket, name, 20);
	}

	return name;
}
